﻿namespace System.ServiceModel.DomainServices
{
    using System;
    using System.Reflection;

    internal class BinaryTypeUtility
    {
        private static ConstructorInfo binaryConstructor;
        private static MethodInfo binaryToArrayMethod;
        private static Type binaryType;
        private const string BinaryTypeFullName = "System.Data.Linq.Binary";

        internal static object GetBinaryFromByteArray(byte[] bytes)
        {
            if (binaryConstructor == null)
            {
                binaryConstructor = binaryType.GetConstructor(new Type[] { typeof(byte[]) });
            }
            return binaryConstructor.Invoke(new object[] { bytes });
        }

        internal static byte[] GetByteArrayFromBinary(object binary)
        {
            if (binaryToArrayMethod == null)
            {
                binaryToArrayMethod = binaryType.GetMethod("ToArray");
            }
            return (byte[]) binaryToArrayMethod.Invoke(binary, null);
        }

        internal static bool IsTypeBinary(Type type)
        {
            if (type != null)
            {
                if (binaryType == type)
                {
                    return true;
                }
                if (string.Compare(type.FullName, "System.Data.Linq.Binary", StringComparison.Ordinal) == 0)
                {
                    binaryType = type;
                    return true;
                }
            }
            return false;
        }
    }
}

